package com.tuanzi.loan.business.service.xhh.settlementsystem.impl;

import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementBill;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementCompany;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementIncome;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementPrepay;
import com.tuanzi.loan.business.repository.xhh.settlementsystem.XhhSettlementBillRepository;
import com.tuanzi.loan.business.repository.xhh.settlementsystem.XhhSettlementIncomeRepository;
import com.tuanzi.loan.business.repository.xhh.settlementsystem.XhhSettlementPrepayRepository;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhBillStatus;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhRemainType;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementBillService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.xhh.settlementsystem.XhhSettlementBillRequest;
import com.tuanzi.loan.vo.response.xhh.settlementsystem.XhhSettlementBillResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author caiwanlin
 * @create 2018-08-24 16:25
 */
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class XhhSettlementBillServiceImpl extends BaseAuditServiceImpl<XhhSettlementBill,Long> implements XhhSettlementBillService {
    @Autowired
    private XhhSettlementBillRepository xhhSettlementBillRepository;

    @Autowired
    private XhhSettlementIncomeRepository xhhSettlementIncomeRepository;

    @Autowired
    private XhhSettlementPrepayRepository xhhSettlementPrepayRepository;

    @Override
    public Page<XhhSettlementBillResponse> list(PageSearcher<XhhSettlementBillRequest> pageSearcher) {
        return xhhSettlementBillRepository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    @Override
    public XhhSettlementBill structureSettlementBill(XhhSettlementCompany xhhSettlementCompany) {
        XhhSettlementBill bill = new XhhSettlementBill();
        bill.setCompanyId(xhhSettlementCompany.getId());
        bill.setCompanyName(xhhSettlementCompany.getCompanyName());
        bill.setBillContent(xhhSettlementCompany.getBillContent());
        bill.setTaxNumber(xhhSettlementCompany.getTaxNumber());
        bill.setBillType(xhhSettlementCompany.getBillType());
        bill.setBankAccount(xhhSettlementCompany.getBankAccount());
        bill.setBankAddress(xhhSettlementCompany.getBankAddress());
        bill.setBankNumber(xhhSettlementCompany.getBankNumber());
        bill.setBillAddress(xhhSettlementCompany.getBillAddress());
        bill.setReceiveName(xhhSettlementCompany.getReceiveName());
        bill.setReceivePhone(xhhSettlementCompany.getReceivePhone());
        bill.setReceiveAddress(xhhSettlementCompany.getReceiveAddress());
        bill.setCompanyPhone(xhhSettlementCompany.getCompanyPhone());
        return bill;
    }

    @Override
    public void onSave(XhhSettlementBill settlementBill, List<Long> selectIncomeId) {
        //保存开票记录
        settlementBill.setBillStatus(XhhBillStatus.COMMISSIONER_CHECK_BILL.index);//财务专员审核
        saveOrUpdate(settlementBill);


        if (settlementBill.getRecordType() == XhhRemainType.EXPEND.index){//消耗记录更改开票状态和关联开票id
            selectIncomeId.forEach(id ->{
                XhhSettlementIncome one = xhhSettlementIncomeRepository.findOne(id);
                one.setBillStatus(XhhBillStatus.COMMISSIONER_CHECK_BILL.index);
                one.setBillId(settlementBill.getId());
                xhhSettlementIncomeRepository.save(one);
            });
        }
        else if (settlementBill.getRecordType() == XhhRemainType.PREPAY.index){
            selectIncomeId.forEach(id->{//预付记录更改开票状态和关联开票id
                XhhSettlementPrepay one = xhhSettlementPrepayRepository.findOne(id);
                one.setBillStatus(XhhBillStatus.COMMISSIONER_CHECK_BILL.index);
                one.setBillId(settlementBill.getId());
                xhhSettlementPrepayRepository.save(one);
            });
        }



    }

    @Override
    public String validateBill(XhhSettlementBill settlementBill) {
        String result = null;

        if (StringUtils.isBlank(settlementBill.getCompanyName())){
            result="开票主体名称为空";
            return result;
        }
        if (settlementBill.getBillContent() == null){
            result="请选择开票内容";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getTaxNumber())){
            result = "开票登记税号为空";
            return result;
        }
        if (settlementBill.getBillType() == null){
            result = "请选择发票类型";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankAccount())){
            result = "开票开户账户为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankAddress())){
            result = "开票开户支行为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankNumber())){
            result = "开票主体名称为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankNumber())){
            result = "开票开户卡号为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBillAddress())){
            result = "开票地址为空";
            return result;
        }
		// if (StringUtils.isBlank(settlementBill.getReceiveName())){
		// result = "开票收件人姓名为空";
		// return result;
		// }
		// if (StringUtils.isBlank(settlementBill.getReceivePhone())){
		// result = "开票收件人手机为空";
		// return result;
		// }
		// if (StringUtils.isBlank(settlementBill.getReceiveAddress())){
		// result = "开票收件地址为空";
		// return result;
		// }
        if (StringUtils.isBlank(settlementBill.getCheckAccount())){
            result = "开票财务审核人为空";
            return result;
        }
        if (settlementBill.getBillAmount() == null){
            result = "开票总结算金额为空";
            return result;
        }
        return null;
    }

    /**
     * 改变开票记录状态
     * @param businessKey
     * @param taskVariables
     */
    @Override
    public void changeBillStatus(String businessKey, Map<String, Object> taskVariables) {
        if (StringUtils.isBlank(businessKey)){
            return;
        }
        long billId = Long.parseLong(businessKey.split(":")[1]);
        XhhSettlementBill bill = xhhSettlementBillRepository.findOne(billId);
        String condition = null;
        Object outcome = taskVariables.get("outcome");
        if (outcome == null){
           return;
        }
        condition = (String) outcome;
        if ("usertask2".equals(condition)){//财务专员审核通过
            bill.setBillStatus(XhhBillStatus.MANAGER_CHECK_BILL.index);
            xhhSettlementBillRepository.save(bill);
            if (bill.getRecordType() == XhhRemainType.EXPEND.index){
                xhhSettlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(XhhBillStatus.MANAGER_CHECK_BILL.index);
                    xhhSettlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == XhhRemainType.PREPAY.index){
                xhhSettlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(XhhBillStatus.MANAGER_CHECK_BILL.index);
                    xhhSettlementPrepayRepository.save(prepay);
                });
            }
        }
        else if ("cancelendevent".equals(condition)){//作废
            bill.setBillStatus(XhhBillStatus.CANCEL.index);
            xhhSettlementBillRepository.save(bill);
            if (bill.getRecordType() == XhhRemainType.EXPEND.index){
                xhhSettlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(XhhBillStatus.NO_BILL.index);
                    income.setBillId(null);
                    xhhSettlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == XhhRemainType.PREPAY.index){
                xhhSettlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(XhhBillStatus.NO_BILL.index);
                    prepay.setBillId(null);
                    xhhSettlementPrepayRepository.save(prepay);
                });
            }
        }
        else if ("passendevent".equals(condition)){//审核通过
            bill.setBillStatus(XhhBillStatus.HAD_BILL.index);
            xhhSettlementBillRepository.save(bill);
            if (bill.getRecordType() == XhhRemainType.EXPEND.index){
                xhhSettlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(XhhBillStatus.HAD_BILL.index);
                    xhhSettlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == XhhRemainType.PREPAY.index){
                xhhSettlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(XhhBillStatus.HAD_BILL.index);
                    xhhSettlementPrepayRepository.save(prepay);
                });
            }
        }
    }

    @Override
    protected JPAAuditRepository<XhhSettlementBill, Long> getRepository() {
        return xhhSettlementBillRepository;
    }
}
